package com.study.zookeeperAPI;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class Zookeeper_Constructor_Usage implements Watcher {

    private static CountDownLatch latch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {

        String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2184";
        ZooKeeper zooKeeper = new ZooKeeper(connectStr, 5000,new Zookeeper_Constructor_Usage());
        latch.await();
        long sessionId = zooKeeper.getSessionId();
        byte [] sessionPassword = zooKeeper.getSessionPasswd();

        //Use illegal sessionId and sessionPassword
        zooKeeper = new ZooKeeper(connectStr, 5000, new Zookeeper_Constructor_Usage(),1L,"test".getBytes());

        //Use correct sesseionId and sessionPassword
        zooKeeper = new ZooKeeper(connectStr, 5000, new Zookeeper_Constructor_Usage(),sessionId, sessionPassword);

        Thread.sleep(Integer.MAX_VALUE);

    }

    public void process(WatchedEvent watchedEvent) {

        System.out.println("Receive watched event:" + watchedEvent);
        if(Event.KeeperState.SyncConnected.equals(watchedEvent.getState())){
            latch.countDown();
        }
    }
}
